import ContentBox from "../../component/ContentBox";
import SwitchTab from "../../component/SwitchTab";
import "./style.css";
import systemPic1 from "../../assets/systemPic1.jpg";
import {
  CloseOutlined,
  CaretLeftOutlined,
  CaretRightOutlined,
} from "@ant-design/icons";
import turang from "../../assets/monitor/turang.png";
import bug from "../../assets/monitor/bug.png";
import drip from "../../assets/monitor/drip.png";
import first from "../../assets/monitor/first.png";
import flower from "../../assets/monitor/flower.png";
import AlertComponet from "../../component/Alert";
import { useState, useEffect, useMemo } from "react";
import {
  facilityList,
  getFacilityPage,
  getListGroup,
  getRiskList,
  townList,
} from "../../api";
import { diva } from "../../global";
import titleImg from "../../assets/title-pic.png";
import CameraComponent from "../../component/Camera";
import huatian from "../../component/idJson";

const SystemPage = () => {
  const [nameChange, setNameChange] = useState("");
  const [option, setOption] = useState([]);
  let selected = false;
  const [facility, setFacility] = useState([]);
  const [facility_count, setFacilityCount] = useState(0);
  const [facility_type_count, setFacilityTypeCount] = useState(0);
  const [town, setTown] = useState([]);
  const [risk, setRisk] = useState([]);
  const [name, setName] = useState("");
  const [val, setVal] = useState(0);
  const [options2, setOption2] = useState([]);
  const [showJumpUp, setJumpUp] = useState(false);
  const [showVideoJumpUp, setVideoJumpUp] = useState(false);

  const [showFacility, setShowFacility] = useState(false);
  const [camera_id, setCameraId] = useState(0);
  const [camera_title, setShowTitle] = useState("");
  const [page, setPage] = useState(1);
  const [pageTotal, setPageTotal] = useState(1);
  const [listFacility, setListFacility] = useState([]);
  const [middleBoxVisible, setMiddleBoxVisible] = useState(false);
  const [videoUrl, setVideoURl] = useState(0);
  const getData = () => {
    townList().then((res) => {
      setTown(res.data.list);
    });
    getRiskList().then((res) => {
      setRisk(res.data.list);
    });
  };
  // 顺序 铜鼓1/2 南腰1/2 李溪1/2 涂大1/2
  const divaTest = async (id, videoId) => {
    const modal = await diva.client?.getEntityById(id);
    const listener = (event) => {
      setVideoJumpUp(true);
      setVideoURl(videoId);
    };
    modal?.addEventListener("click", listener);
    return () => {
      modal.setWebWidget(null);
    };
  };

  const getChildrenValue = (val, name) => {
    if (val === 0 || name === undefined) {
      setMiddleBoxVisible(false);
    }
    setName(name);
    setVal(val);
    setPage(1);
    facilityList({ town_id: !name ? null : val }).then((res) => {
      setFacility(res.data.list);
      setFacilityCount(res.data.count);
      setFacilityTypeCount(res.data.typeCount);
    });
    getRiskList({ town_id: !name ? null : val }).then((res) => {
      setRisk(res.data.list);
    });
    if (val !== 0 && val !== 1&&name!==undefined) {
      diva.client?.applyScene(`${name + "监测"}`);
      setTimeout(() => {
        getListGroup({ town_id: val })
          .then((res) => {
            res.data.list.length > 0 &&
              res.data.list.map((item) => changeDikuai(item));
          })
          .catch((err) => console.log(err));
      }, 1000);
    } else {
      return;
    }


  };

  const getFacilityListPage = () => {
    getFacilityPage({ town_id: name ? val : 0, page: page, size: 9 }).then(
      (res) => {
        setListFacility(res.data.list);
        setPageTotal(res.data.pageTotal);
      }
    );
  };
  const changeDikuai = async (item) => {
    const modal = await diva.client?.getEntityById(item.icon_id);
    const listener = (event) => {
      diva.client
        ?.applyScene(item.scene)
        .then( () => {
            divaTest(item.entity_id, item.id);
            divaTest(item.show_tag_id, item.id);
        })
        .catch((err) => console.log(err));
      //   divaTest(facility[val.id]?.position_id, facility[val.id]?.id);
      //   divaTest(facility[val.id]?.show_tag_id, facility[val.id]?.id);
    };
    modal?.addEventListener("click", listener);
  };
  useEffect(() => {
    getFacilityListPage();
  }, [page, name]);

  const getSearchInfo = (val) => {
    facilityList(val).then((res) => {
      setFacility(res.data.list);
    });
    setOption([
      { name: "开启", id: 1, selected: !selected },
      { name: "关闭", id: 0, selected: false },
    ]);
    setOption2([
      { name: "自动", id: 1, selected: !selected },
      { name: "手动", id: 2, selected: false },
    ]);
  };
  const tableIndex = (val) => {
    if (facility[val.id]?.scene) {
      diva.client
        ?.applyScene(facility[val.id]?.scene)
        .then(() => {})
        .catch((err) => console.log(err));
    }
    if (facility[val.id]?.position_id) {
      divaTest(facility[val.id]?.position_id, facility[val.id]?.id);
      divaTest(facility[val.id]?.show_tag_id, facility[val.id]?.id);
    }
  };

  const getGroupId = async () => {
    diva.client
      ?.request("GetEntityIds", {
        group: "总摄像标记/涂市镇摄像", // 资源列表中从根目录开始的路径
      })
      .then(async (res) => {
        const modal = await diva.client?.getEntityById(res.result[0]);
        const modal2 = await diva.client?.getEntityById(res.result[1]);

        const listener = (event) => {
          setNameChange("涂市镇");
          setMiddleBoxVisible(true);
          diva.client
            ?.applyScene("涂市镇监测")
            .then(() => {})
            .catch((err) => console.log(err));
        };
        modal?.addEventListener("click", listener);
        modal2?.addEventListener("click", listener);
      })
      .catch((err) => console.log(err));
    diva.client
      ?.request("GetEntityIds", {
        group: "总摄像标记/李溪镇摄像", // 资源列表中从根目录开始的路径
      })
      .then(async (res) => {
        const modal = await diva.client?.getEntityById(res.result[0]);
        const modal2 = await diva.client?.getEntityById(res.result[1]);

        const listener = (event) => {
          setNameChange("李溪镇");
          setMiddleBoxVisible(true);

          diva.client
            ?.applyScene("李溪镇监测")
            .then(() => {})
            .catch((err) => console.log(err));
        };
        modal?.addEventListener("click", listener);
        modal2?.addEventListener("click", listener);
      })
      .catch((err) => console.log(err));
    diva.client
      ?.request("GetEntityIds", {
        group: "总摄像标记/铜鼓镇摄像", // 资源列表中从根目录开始的路径
      })
      .then(async (res) => {
        const modal = await diva.client?.getEntityById(res.result[0]);
        const modal2 = await diva.client?.getEntityById(res.result[1]);

        const listener = (event) => {
          setNameChange("铜鼓镇");
          setMiddleBoxVisible(true);

          diva.client
            ?.applyScene("铜鼓镇监测")
            .then(() => {})
            .catch((err) => console.log(err));
        };
        modal?.addEventListener("click", listener);
        modal2?.addEventListener("click", listener);
      })
      .catch((err) => console.log(err));
    diva.client
      ?.request("GetEntityIds", {
        group: "总摄像标记/花田乡摄像", // 资源列表中从根目录开始的路径
      })
      .then(async (res) => {
        const modal = await diva.client?.getEntityById(res.result[0]);
        const modal2 = await diva.client?.getEntityById(res.result[1]);

        const listener = (event) => {
          setNameChange("花田乡");
          setMiddleBoxVisible(true);

          diva.client
            ?.applyScene("花田乡监测")
            .then(() => {})
            .catch((err) => console.log(err));
        };
        modal?.addEventListener("click", listener);
        modal2?.addEventListener("click", listener);
      })
      .catch((err) => console.log(err));
    diva.client
      ?.request("GetEntityIds", {
        group: "总摄像标记/南腰界镇摄像", // 资源列表中从根目录开始的路径
      })
      .then(async (res) => {
        const modal = await diva.client?.getEntityById(res.result[0]);
        const modal2 = await diva.client?.getEntityById(res.result[1]);

        const listener = (event) => {
          setNameChange("南腰界镇");
          setMiddleBoxVisible(true);

          diva.client
            ?.applyScene("南腰界镇监测")
            .then(() => {})
            .catch((err) => console.log(err));
        };
        modal?.addEventListener("click", listener);
        modal2?.addEventListener("click", listener);
      })
      .catch((err) => console.log(err));
  };
  const titleChangeName = (val) => {};

  const thisContent = useMemo(() => {
    return (
      <ContentBox
        middleBoxName={name}
        setSelect={getSearchInfo}
        tableIndex={tableIndex}
        title={"设备总量"}
        infoFirstTab={[
          { title: "设备数量", count: facility_count },
          { title: "运行状态", count: "正常" },
        ]}
        infoSecondTab={[{ title: "设备类型", count: facility_type_count }]}
        selectFirst={[
          {
            title: "设备状态",
            key: "status",
            options: [
              { name: "开启", id: 1 },
              { name: "关闭", id: 0 },
            ],
          },
          { title: "控制类型", key: "control_type", options: options2 },
        ]}
        selectSecond={[
          {
            title: "运行状态",
            key: "run_status",
            options: [
              { name: "正常", id: 1 },
              { name: "异常", id: 0 },
            ],
          },
        ]}
        tableListName={["设备编号", "运行状态", "设备开关", "位置"]}
        fengxian={1}
        tableList={facility}
      />
    );
  });
  useEffect(() => {
    getData();
    getGroupId();
    
    getFacilityPage({page:1, size:9}).then(
      (res) => {
        setListFacility(res.data.list);
        setPageTotal(res.data.pageTotal);
      }
    );
    // divaTest();
    // return(())
    setOption([
      { name: "开启", id: 1, selected: selected },
      { name: "关闭", id: 0, selected: false },
    ]);
    setOption2([
      { name: "自动", id: 1, selected: selected },
      { name: "手动", id: 2, selected: false },
    ]);
  }, []);

  //监测系统页面

  return (
    <div className="">
      <SwitchTab
        title={town}
        setParentProps={getChildrenValue}
        index={1}
        nameChange={nameChange}
        layout={middleBoxVisible}
      />
      <AlertComponet />

      <div className="system-container">
        <div className="content-left">
          <ContentBox title="实景融合点位" pic={systemPic1} />
          <ContentBox
            title="风险预警提示"
            tableListName={["事件", "设备标号", "负责人电话", "状态"]}
            fengxian={1}
            tableList={risk}
          />
        </div>
        <div className="content-right">
          <ContentBox
            title="功能监测系统"
            iconAndTextFirstColumn={[
              { title: "摄像监测", icon: first },
              { title: "苗情监测", icon: flower },
            ]}
            iconAndTextSecondColumn={[
              { title: "土壤监测", icon: turang },
              { title: "水质监测", icon: drip },
            ]}
            iconAndTextThirdColumn={[{ title: "虫害监测", icon: bug }]}
          />
          {thisContent}
        </div>
      </div>
      {showJumpUp && (
        <div className="sx-jumpUp-contain">
          <div className="sx-jumpup-title">
            <div className="sx-jump-up-title">
              <img src={titleImg} />
              <div>全局监控预览</div>
            </div>

            <div>
              <CloseOutlined onClick={() => setJumpUp(false)} />
            </div>
          </div>
          <div className="camera-detail">
            {listFacility.map((item, _index) => (
              <div
                className="sx-list"
                key={item.id}
                onClick={() => {
                  setCameraId(item.id);
                  setShowTitle(item.pos);
                  setShowFacility(true);
                  setJumpUp(false);
                }}
              >
                <div className="sx-list-title">{item.pos}</div>
                <div>
                  <img src={item.discover} />
                </div>
              </div>
            ))}

            <div className="list-pagination-fa">
              {/* 这边是调用案例 */}
              <CaretLeftOutlined
                onClick={() => {
                  if (page > 1) {
                    setPage(page - 1);
                  }
                }}
              />
              <span>
                {page}/{pageTotal}
              </span>
              <CaretRightOutlined
                onClick={() => {
                  if (page < pageTotal) {
                    setPage(page + 1);
                  }
                }}
              />
            </div>
          </div>
        </div>
      )}

      {showFacility && (
        <div className="sx-jumpUp-contain">
          <div className="sx-jumpup-title">
            <div className="sx-jump-up-title">
              <img src={titleImg} />
              <div>全局监控预览——{camera_title}</div>
            </div>

            <div>
              <CloseOutlined
                onClick={() => {
                  setJumpUp(true);
                  setShowFacility(false);
                }}
              />
            </div>
          </div>
          <div className="camera-detail">
            <CameraComponent camera_id={camera_id} />
          </div>
        </div>
      )}
      {showVideoJumpUp && (
        <div className="sx-jumpUp-contain">
          <div className="jumpup-title">
            <div className="jump-up-title">
              <img src={titleImg} />
              <div>自媒体矩阵网红推流画面</div>
            </div>

            <div>
              <CloseOutlined onClick={() => setVideoJumpUp(false)} />
            </div>
          </div>
          <div className="camera-detail">
            <CameraComponent camera_id={videoUrl} />
            {/*<img className='jumpUp-img' src={defaultPic} />*/}
          </div>
        </div>
      )}
      <div
        className="jk"
        onClick={() => {
          setJumpUp(true);
          setShowFacility(false);
        }}
      >
        全局监控预览
      </div>
    </div>
  );
};
export default SystemPage;
